// bug:1、字体展开后hover效果还在，无法去除
// 编辑区
let $editor = (function () {
  let $editorDOM = $('<div class = "notepad-editor">'
    + '<textarea spellcheck="false"></textarea>'
    + '</div>'
  );

  let $textArea = $editorDOM.find('textarea');

  show = () => {
    $('body').append($editorDOM);
    $textArea.trigger('focus');
  }

  return { show: show }
}());
// 状态栏
let $statusBar = (function () {
  let $statusBarDOM = $(''
    + '<div class = "notepad-statusbar">'
    + '<div class = "left-panel"></div>'
    + '<div class = "right-panel">'
    + '<p class = "row-col"></p>'
    + '</div>'
    + '</div>'
  )

  let $rowCol = $statusBarDOM.find('.row-col'),
    // 默认
    cfg = { row: 1, col: 1 };
  setRowCol = (r, c) => {
    $rowCol.html(`第${r}行，第${c}列`);
  }

  init = (conf) => {
    // 合并
    $.extend(cfg, conf);
    setRowCol(cfg.row, cfg.col);
    $('body').append($statusBarDOM);
  }

  return { init: init }
}())
// 菜单栏
let $menuBar = (function () {
  let menuslist = [
    {
      title: "文件(F)",
      menu: [{ title: "新建(N)", handlr: function () { console.log('点击事件'); } }, { title: "新窗口(W)", handlr: function () { console.log('点击事件'); } }, { title: "打开(O)", handlr: function () { console.log('点击事件'); } }, { title: "保存(S)", handlr: function () { console.log('点击事件'); } }, { title: "另存为(A)", handlr: function () { console.log('点击事件'); } }, { title: "页面设置(U)", handlr: function () { console.log('点击事件'); } }, { title: "打印(X)", handlr: function () { console.log('点击事件'); } }, { title: "退出(X)", handlr: function () { console.log('点击事件'); } }]
    },
    {
      title: "编辑(E)",
      menu: [{ title: "撤销(U)", handlr: function () { console.log('点击事件'); } }, { title: "剪切(T)", handlr: function () { console.log('点击事件'); } }, { title: "复制(C)", handlr: function () { console.log('点击事件'); } }, { title: "粘贴(P)", handlr: function () { console.log('点击事件'); } }, { title: "删除(L)", handlr: function () { console.log('点击事件'); } }, { title: "用Bing搜索", handlr: function () { console.log('点击事件'); } }, { title: "查找(F)", handlr: function () { console.log('点击事件'); } }, { title: "查找下一个(N)", handlr: function () { console.log('点击事件'); } }, { title: "查找上一个(V)", handlr: function () { console.log('点击事件'); } }, { title: "替换(R)", handlr: function () { console.log('点击事件'); } }, { title: "转到(G)", handlr: function () { console.log('点击事件'); } }, { title: "全选(A)", handlr: function () { console.log('点击事件'); } }, { title: "时间/日期(D)", handlr: function () { console.log("点击事件"); } }]
    },
    {
      title: "格式(O)",
      menu: [{ title: "自动换行(W)", handlr: function () { console.log('点击事件'); } }, {
        title: "字体(F)...", handlr: function () {
          // 点击菜单取消展开
          $('.notepad-editor').trigger("click");
          // 字体面板展开
          $('.notepad-dlg-mask').show();
          // 设置遮罩层
          $('body').append($('<div class = "notchange"></div>'))
          return false
        }
      }]
    },
    {
      title: "查看(V)",
      menu: [{ title: "缩放(Z)", handlr: function () { console.log('点击事件'); } }, { title: "状态栏(S)", handlr: function () { console.log('点击事件'); } }]
    },
    {
      title: "帮助(H)",
      menu: [{ title: "查看帮助(H)", handlr: function () { console.log('点击事件'); } }, { title: "发送反馈(F)", handlr: function () { console.log('点击事件'); } }, { title: "关于记事本(A)", handlr: function () { console.log('点击事件'); } }]
    },
  ]
  let $menus = $('<div class = "notepad-menu"></div>');
  let menus = [];
  let detailst = []
  // 创建标题项
  createTitle = () => {
    let $titles = $('<div class = "menus-titles"></div>');

    for (let i = 0; i < menuslist.length; i++) {
      let $title = $('<dl class = "menu-title"></dl>');
      var index = -1;
      $title.html(menuslist[i].title);
      $titles.append($title);
      menus[i] = $title;
      // -1,0~4
      // 在未有菜单展开的时候无法打开,有菜单的时候才能出发hover
      $title.hover(() => {
        // 处理hover所有菜单当hover时会变色,并且只有别的菜单先展开才会有别的hover展开
        menus[$title.index()].css({
          "background-color": "#cce8ff",
          "border": "1px solid #bedffb;"
        })
        for (let j = 0; j < menus.length; j++) {
          if ($title.index() !== j) {
            menus[j].css({
              "background-color": "#fff"
            })
          }
        }
        // index>-1的时候是由菜单点击事件触发
        if (index > -1) {
          index = $title.index();
          menus[index].find('.menus-details').css({
            "display": "block",
            "background-color": "#f0f0f0"
          })
          for (let j = 0; j < menus.length; j++) {
            if (index !== j) {
              menus[j].find('.menus-details').css({
                "display": "none",
              })
            }
          }
        }
        return false
      })
      // 点击菜单之后的展开
      $title.click(() => {
        // 点击事件简单
        index = $title.index();
        menus[index].css({
          "background-color": "#cce8ff",
          "border": "1px solid #bedffb;"
        })
        menus[index].find('.menus-details').css({
          "display": "block",
          "background-color": "#f0f0f0"
        })
        for (let j = 0; j < menus.length; j++) {
          if (index !== j) {
            menus[j].css({
              "background-color": "#fff"
            })
            menus[j].find('.menus-details').css({
              "display": "none",
            })
          }
        }
        return false
      })
      // 点击隐藏
      $('.notepad-editor').click(() => {
        // >-1能找到但是赋值-1也会触发该事件所以要if剔除-1情况
        if (index > -1) {
          menus[index].find('.menus-details').css({
            "display": "none",
          })
          menus[index].css({
            "background-color": "#fff"
          })
          index = -1
        }
        return false
      })
      // 创建详细的菜单
      createDetail(i, $title)
    }
    // 将菜单放入DOM中
    $menus.append($titles);
  }

  createDetail = (i, $title) => {
    let $details = $('<dd class = "menus-details"></dd>');
    for (let j = 0; j < menuslist[i].menu.length; j++) {
      let $detail = $('<dt class = "menus-detail"></dt>');
      $detail.html(menuslist[i].menu[j].title);

      $details.append($detail);
      $details.hide()
      detailst[j] = $detail;

      $detail.click(() => {
        menuslist[i].menu[j].handlr();
        // 去除事件冒泡
        return false
      })
    }
    $title.append($details);
  }
  // 废弃函数
  disable = (m, n) => {
    $($($menus.find('.menu-title')[m]).find('.menus-detail')[n]).addClass('disable')
  }
  // 插入函数

  destorymenus = (index) => {
    let $test = $($('.menus-details')[index]);
    // console.log($test);
    $test.css('display', 'none');
  }

  init = () => {
    createTitle();
    $('body').append($menus);
  }

  return { init: init, disable: disable, destorymenus: destorymenus }
}())
// 字体格式更改
let $fontStyle = (function () {
  let $dlg = $('<div class="notepad-dlg-mask notepad-dlg-font">'
    + '<div class="dialogbox notepad-dlgbox">'
    + '<div class="notepad-dlg-titlebar">'
    + '<p class="title">字体</p>'
    + '<span class="close-btn">✖</span>'
    + '</div>'
    + '<div class="main notepad-dlg-main">'
    + '<div class="font-family"><p>字体(F):</p></div>'
    + '<div class="font-style"><p>字形(Y):</p></div>'
    + '<div class="font-size"><p>大小(S):</p></div>'
    + '<fieldset class="sample">'
    + '<legend>示例</legend>'
    + '<p>AaBbYyZz</p>'
    + '</fieldset>'
    + '<div class="script">'
    + '<label>'
    + '脚本(R):<br>'
    + '<select class = "choise">'
    + '<option value="西欧语言">西欧语言</option>'
    + '<option value="中文 GB2312">中文 GB2312</option>'
    + '</select>'
    + '</label>'
    + '</div>'
    + '<input class="btn-ok btn" type="button" value="确定">'
    + '<input class="btn-cancel btn" type="button" value="取消">'
    + '<p class = "morestyle">显示更多字体</p>'
    + '</div>'
    + '</div>'
    + '</div>');
  let fonts = ['SimSun', 'SimHei', 'Arial', 'Microsoft YaHei', 'NSimSun', 'KaiTi', 'Microsoft JhengHei', 'PMingLiU'];
  let styles = ['常规', '斜体', '粗体', '粗偏斜体'];
  let sizes = ['8', '9', '10', '11', '12', '14', '16', '18', '20', '22', '24', '26', '28', '36'];
  // 向指定的DOM中插入列表
  let list = [];

  // 默认字体Arial 默认大小14 默认样式常规
  let cfg = { font: 'Arial', style: '常规', size: '14' };
  let StoreCfg = { font: 'Arial', style: '常规', size: '14' };
  createListFont = (DomName, list) => {
    let $listdiv = $(`<div class = listdiv></div>`);

    // 插入上方input输入框吧
    let $listshowinput = $(`<input class = "listshowinput" type = "text" value="测试"/>`)

    $listdiv.append($listshowinput);

    // 遍历列表
    let $items = $('<ul class = "listitems"></ul>');
    for (let i = 0; i < list.length; i++) {
      let $item = $('<li class = "listitem"></li>');
      let index = -1;
      $item.html(list[i]);
      $items.append($item);
      list[i] = $item;

      // 选择默认

      $item.click(() => {
        let length = $item.siblings().length + 1;
        let num = whichSeletc(length);
        let confg = { font: '', style: '', size: '' };
        index = $item.index();

        console.log(num, index);

        if (num === 0) {
          confg.font = $(list[index]).html();
        }
        if (num === 1) {
          confg.style = $(list[index]).html();
        }
        if (num === 2) {
          confg.size = $(list[index]).html();
        }
        BackChange(list, index);

        // 上方是样式的操作
        // 下方是样式的操作

        Selected(confg, num, index, list);
        return false
      })
    }
    $listdiv.append($items);

    DomName.append($listdiv);
  }

  destory = () => {
    $('.notepad-dlg-mask').hide();
    $('.notchange').remove();
  }

  // 选择2.0
  Selected = (confg, num, index, list) => {
    let style = 'normal';
    if (confg.font !== '') {
      cfg.font = confg.font
    }
    if (confg.style !== '') {
      cfg.style = confg.style
    }
    if (confg.size !== '') {
      cfg.size = confg.size
    }
    console.log(num);
    $($('.listdiv').find('input')[num]).val($(list[index]).html());


    $($('.sample').find('p')).css({
      "font-family": `${cfg.font}`,
      "font-size": `${cfg.size}px`
    })
    selectFontStyles($($('.sample').find('p')), cfg.style)
    // console.log(cfg);
  }

  BackChange = (list, index) => {
    $(list[index]).addClass('selected');
    list[index].css({
      "background-color": "lightblue"
    })
    for (let j = 0; j < list.length; j++) {
      if (j !== index) {
        list[j].css({
          "background-color": "#fff"
        })
      }
    }
  }

  // 字体样式
  selectFontStyles = (item, style) => {
    if (style === '常规') {
      item.css({ 'font-style': 'normal', 'font-weight': 'normal' });
      return;
    }
    if (style === '斜体') {
      item.css({ 'font-style': 'italic', 'font-weight': 'normal' });
      return;
    }
    if (style === '粗体') {
      item.css({ 'font-weight': 'bold', "font-style": "normal" });
      return;
    }

    if (style === '粗偏斜体') {
      item.css({ 'font-weight': 'bold', 'font-style': 'italic' });
      return;
    }
  }

  // 选择语言
  selectLan = (item, lan) => {
    if (lan === "西欧语言") {
      item.html('AaBbYyZz')
      return
    }
    if (lan === "中文 GB2312") {
      item.html('刘志伟写')
      return
    }
  }

  // 父元素下标获取不了，只能出此下策，没有普适性，bug是当数组一样长度时无法判断
  whichSeletc = (length) => {
    let index = -1
    if (length == fonts.length) {
      index = 0
      return index
    }
    if (length == styles.length) {
      index = 1
      return index
    }
    if (length == sizes.length) {
      index = 2
      return index
    }
    return index
  }

  defauSelect = (list) => {
    $($('.listdiv').find('input')[0]).val(cfg.font);
    $($('.listdiv').find('input')[1]).val(cfg.style);
    $($('.listdiv').find('input')[2]).val(cfg.size);
    console.log($('.listitem'));
    // $('.listitem')
    $($('.listitem')[2]).css({
      "background-color": "lightblue"
    })
    $($('.listitem')[8]).css({
      "background-color": "lightblue"
    })
    $($('.listitem')[17]).css({
      "background-color": "lightblue"
    })
  }
  // 创建
  init = () => {
    $('body').append($dlg);

    // 创建三个列表
    createListFont($('.font-family'), fonts);
    createListFont($('.font-style'), styles);
    createListFont($('.font-size'), sizes);

    // 点击隐藏
    $('.close-btn').click(() => {
      destory();
      return false
    })
    $('.btn-cancel').click(() => {
      destory();
      return false
    })
    // 样式发生变化
    $('.btn-ok').click(() => {
      destory();
      $('textarea').css({
        "font-family": `${cfg.font}`,
        "font-size": `${cfg.size}px`
      });
      selectFontStyles($('textarea'), cfg.style)
      return false
    })
    // 拖拽
    $('.notepad-dlg-mask').draggable({ handle: $('.notepad-dlg-titlebar') })

    // 改变展示框
    $('.choise').change(() => {
      let value = $('select  option:selected').val();
      selectLan($($('.sample').find('p')), value)
    })
    // selectFamily()
    defauSelect()
  }
  return { init: init }
}())